package com.mygame.arena.business;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mygame.arena.error.ArenaError;
import com.mygame.db.entity.manager.ArenaManager;
import com.mygame.game.common.IGameMessage;
import com.mygame.game.message.xinyue.BuyArenaChallengeTimesMsgRequest;
import com.mygame.game.message.xinyue.BuyArenaChallengeTimesMsgResponse;
import com.mygame.game.messagedispatcher.GameMessageHandler;
import com.mygame.game.messagedispatcher.GameMessageMapping;
import com.mygame.game.rpc.ConsumeDiamonRPCResponse;
import com.mygame.game.rpc.ConsumeDiamondRPCRequest;
import com.mygame.gateway.message.context.GatewayMessageContext;
import com.mygame.gateway.message.context.UserEvent;
import com.mygame.gateway.message.context.UserEventContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.Promise;

@GameMessageHandler
public class ArenaBusinessHandler {
    private Logger logger = LoggerFactory.getLogger(ArenaBusinessHandler.class);

    @UserEvent(IdleStateEvent.class)
    public void idleStateEvent(UserEventContext<ArenaManager> ctx, IdleStateEvent event, Promise<Object> promise) {
        logger.debug("收到空闲事件：{}", event.getClass().getName());
        ctx.getCtx().close();
    }
    @GameMessageMapping(BuyArenaChallengeTimesMsgRequest.class)
    public void buyChallengeTimes(BuyArenaChallengeTimesMsgRequest request, GatewayMessageContext<ArenaManager> ctx) {
        // 先通过rpc扣除钻石，扣除成功之后，再添加挑战次数
        BuyArenaChallengeTimesMsgResponse response = new BuyArenaChallengeTimesMsgResponse();
        Promise<IGameMessage> rpcPromise = ctx.newRPCPromise();
        rpcPromise.addListener(new GenericFutureListener<Future<IGameMessage>>() {
            @Override
            public void operationComplete(Future<IGameMessage> future) throws Exception {
                if (future.isSuccess()) {
                    ConsumeDiamonRPCResponse rpcResponse = (ConsumeDiamonRPCResponse) future.get();
                    int errorCode = rpcResponse.getHeader().getErrorCode();
                    if (errorCode == 0) {
                        ctx.getDataMaanger().addChallengeTimes(10);// 假设添加10次竞技场挑战次
                        logger.debug("购买竞技挑战次数成功");
                    } else {
                        response.getHeader().setErrorCode(errorCode);
                    }
                } else {
                    response.getHeader().setErrorCode(ArenaError.SERVER_ERROR.getErrorCode());
                }
                ctx.sendMessage(response);
            }
        });
        ConsumeDiamondRPCRequest rpcRequest = new ConsumeDiamondRPCRequest();
        rpcRequest.getBodyObj().setConsumeCount(20);// 假设是20钻石
        ctx.sendRPCMessage(rpcRequest, rpcPromise);
    }
}
